package com.leyou.trade.interceptor;

import com.leyou.common.constants.UserTokenConstants;
import com.leyou.common.entity.Payload;
import com.leyou.common.entity.UserInfo;
import com.leyou.common.exceptios.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.common.utils.JwtUtils;
import com.leyou.trade.utils.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

/**
 * @author 虎哥
 */
public class UserInterceptor implements HandlerInterceptor {
    /**
     * 会在Controller方法执行前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            // 1.获取token
            String token = CookieUtils.getCookieValue(request, UserTokenConstants.COOKIE_NAME);
            if(StringUtils.isBlank(token)){
                // 没有用户信息，抛异常
                throw new LyException(401, "没有登录，无法访问！");
            }
            // 2.解析token，不验证
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, UserInfo.class);
            // 3.获取用户
            UserInfo userInfo = payload.getUserInfo();
            // 4.存储
            UserHolder.setUser(userInfo.getId());
            // 5.true就放行
            return true;
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("解析token失败！");
        }
    }

    /**
     * 会在preHandle返回false后执行，或者之前抛出异常后执行，或者视图渲染后执行
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 移除用户
        UserHolder.remove();
    }
}
